package com.zmm.myyimixian.ui.activity.main.home.childFragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.zmm.myyimixian.MyApp;
import com.zmm.myyimixian.R;
import com.zmm.myyimixian.base.BaseFragment;
import com.zmm.myyimixian.bean.HomeBoos;
import com.zmm.myyimixian.config.ConfigPath;
import com.zmm.myyimixian.db.DataDao;
import com.zmm.myyimixian.db.ShoppingCart;
import com.zmm.myyimixian.ui.activity.main.home.MyHomeBoosThread;
import com.zmm.myyimixian.ui.activity.main.home.MyListView;
import com.zmm.myyimixian.ui.adapter.MyHomeChildApater;
import com.zmm.myyimixian.util.UIManager;

import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * A simple {@link Fragment} subclass.
 */
public class ChildFragment extends BaseFragment implements MyHomeChildApater.ModifyCountInterface {


    @BindView(R.id.boss_list_prlv)
    MyListView bossListPrlv;
    @BindView(R.id.boss_xianshi_iv)
    ImageView bossXianshiIv;
    @BindView(R.id.boss_sx_ptrsv)
    PullToRefreshScrollView bossSxPtrsv;
    private String path;
    private MyHandler handler = new MyHandler(this);
    private MyHomeChildApater apater;
    private int ItemCount = 0;
    private List<HomeBoos.GoodsBean> goods;

    public static ChildFragment getBundle(String id) {
        ChildFragment fragment = new ChildFragment();
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        // 传入参数
        fragment.setArguments(bundle);
        return fragment;
    }

    public ChildFragment() {
        // Required empty public constructor
    }


    @Override
    public void initView(View view) {
        Bundle bundle = getArguments();
        String id = bundle.getString("id");
        path = ConfigPath.getHomeBoos(id);
        new MyHomeBoosThread(handler, path).start();
        apater = new MyHomeChildApater();
        bossListPrlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HomeBoos.GoodsBean goodsBean = goods.get(position);
                String desc_url = goodsBean.getDesc_url();
                if ("1".equals(goodsBean.getIs_buying_group())) {
                    UIManager.startGroupPurchase(getActivity(), desc_url);
                } else {
                    UIManager.startDetails(getActivity(), desc_url);
                }
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_child;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    //数量的加和初始创建
    @Override
    public void doIncrease(int position, TextView showCountView, ImageButton jian, ImageButton jia, int count) {
        MyApp.isSJK = false;
        ItemCount = Integer.valueOf(showCountView.getText().toString());
        HomeBoos.GoodsBean goodsBean = goods.get(position);
        if (ItemCount == 0) {
            ItemCount = 1;
            jian.setVisibility(View.VISIBLE);
            showCountView.setVisibility(View.VISIBLE);
            showCountView.setText("1");
            apater.notifyDataSetChanged();
            DataDao.addShoppingCart(goodsBean.getImg(), goodsBean.getName(), goodsBean.getUnit_desc(), goodsBean.getUnit_price(), "1", goodsBean.getPromotion_img(), new SaveListener() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onFailure(int i, String s) {
                    Toast.makeText(getActivity(), "没有网络", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            ++ItemCount;
            String valueOf = String.valueOf(ItemCount);
            showCountView.setText(valueOf);
            apater.notifyDataSetChanged();
            DataDao.setShoppingCart(goodsBean.getName(), valueOf);
        }
    }

    @Override
    public void doDecrease(int position, TextView showCountView, ImageButton jian, ImageButton jia, int count) {
        MyApp.isSJK = false;
        String deletname = goods.get(position).getName();
        ItemCount = Integer.valueOf(showCountView.getText().toString());
        --ItemCount;
        final String text = String.valueOf(ItemCount);
        if (ItemCount < 1) {
            showCountView.setText(text);
            jian.setVisibility(View.GONE);
            showCountView.setVisibility(View.GONE);
            apater.notifyDataSetChanged();
            DataDao.deleteShoppingCart(goods.get(position).getName(), new DeleteListener() {
                @Override
                public void onSuccess() {
                    MyApp.isSJK = true;
                }

                @Override
                public void onFailure(int i, String s) {

                }
            });
        } else {
            showCountView.setText(text);
            apater.notifyDataSetChanged();
            DataDao.setShoppingCart(deletname, text);
        }
    }

    //获取网上下载的数据
    private class MyHandler extends Handler {

        private WeakReference<ChildFragment> reference = null;

        public MyHandler(ChildFragment childFragment) {
            reference = new WeakReference<>(childFragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ChildFragment childFragment = reference.get();
            if (childFragment != null) {
                if (msg.what == 1) {
                    HomeBoos homeBoos = (HomeBoos) msg.obj;
                    goods = homeBoos.getGoods();
                    setDatas(goods);
                    if (homeBoos.getBanners().size() != 0) {
                        String image = homeBoos.getBanners().get(0).getImage();
                        if (image != null) {
                            bossXianshiIv.setVisibility(View.VISIBLE);
                            Glide.with(getActivity()).load(ConfigPath.getLunBoPath(image)).placeholder(R.mipmap.icon_home_item_default).into(bossXianshiIv);
                        }
                    }else {
                        bossXianshiIv.setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    //给适配器传送数据
    private void setDatas(List<HomeBoos.GoodsBean> goods) {
        apater.setData(goods);
        bossListPrlv.setAdapter(apater);
        apater.setModifyCountInterface(ChildFragment.this);
    }

    //获得购物车数据库数据
    private void initData() {
        if (MyApp.isLogin()) {
            MyApp.isSJK = true;
            DataDao.getAllShoppingCarts(new FindListener<ShoppingCart>() {
                @Override
                public void onSuccess(List<ShoppingCart> list) {
                    apater.setShuJuKu(list);
                }

                @Override
                public void onError(int i, String s) {

                }
            });
        }
    }

    //获取焦点后刷新数据库数据
    @Override
    public void onResume() {
        super.onResume();
        if (MyApp.isLogin()) {
            initData();
        }
    }
}
